//
//  GetMessageAuthCodeLabel.m
//  UILbrary
//
//  Created by mac on 16/12/5.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "GetMessageAuthCodeLabel.h"
@interface GetMessageAuthCodeLabel()


/**
 计时对象
 */
@property (nonatomic, strong) NSTimer *myTime;


/**
 倒计时 时间
 */
@property (nonatomic, assign) NSInteger countDownSeconds;

@property (nonatomic, copy) startCoutDown coutDownBlock;
@end
@implementation GetMessageAuthCodeLabel



#pragma mark - init

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self addGesterEvent];
    }
    
    return self;
}


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {

    }
    
    return self;
}

- (instancetype)init{
    if (self = [super init]) {

        [self addGesterEvent];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    if (_countDownSeconds <=0 ) {
       [self configUI];
    }
}

- (void)configUI{
    self.backgroundColor = _normalColor;
    self.text = _normalTitle;
    _countDownSeconds = _seconds;
}

/**
 添加手势
 */
- (void)addGesterEvent{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureEvent)];

    [self addGestureRecognizer:tap];
}


#pragma mark -private methods




#pragma mark - event response



/**
 单击手势代理
 */
- (void)tapGestureEvent{
    
    if ([self.delegate respondsToSelector:@selector(clickEventIsStartContDown:)]) {
        [self.delegate clickEventIsStartContDown:^(BOOL isStart) {
            
            if (isStart)
            {
                [self fireTime];
            }
            
        }];
    }
}


/**
 刷新倒计时数字
 */
- (void)refreshLabelTitle{
    self.userInteractionEnabled = NO;
    
    self.backgroundColor = _selectColor;
    _countDownSeconds--;
    if (_countDownSeconds <=0 ) {
        _countDownSeconds = _seconds;
        self.text = _normalTitle;
        self.userInteractionEnabled = YES;
        self.backgroundColor = _normalColor;
        [self stopTime];
        return;
    }
    self.text = [NSString stringWithFormat:@"%@ %ld",_selectTitle,_countDownSeconds];
}


/**
 暂停 time
 */
- (void)stopTime{
    [self.myTime invalidate];
    _myTime = nil;
}

/**
  启动time
 */
- (void)fireTime{
    
    [self.myTime fire];
}


#pragma mark - setter getter

- (NSTimer *)myTime{
    if (!_myTime) {
        _myTime = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshLabelTitle) userInfo:nil repeats:YES];
    }
    return _myTime;
}


@end
